import { Module } from 'vuex'
import { getRouters } from '@/api/menu'
import { asyncRoutes, constantRoutes } from '@/router/index'
import { tabPaneProps } from 'element-plus'
/**
 * 使用 meta.role 来确定当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(user, route) {
  if (route.meta && (route.meta.roles || route.meta.permissions)) {
    return user.roles?.some(role => route.meta.roles?.includes(role?.roleKey)) ||
      user.permissions?.some(permission => route.meta.permissions?.some(x => permission.includes(x)))
  } else {
    return true
    // return false
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param user
 */
export function filterAsyncRoutes(routes, user) {

  const res = []
  // console.log(routes)
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(user, tmp)) {
      if (tmp.children?.length) {
        tmp.children = filterAsyncRoutes(tmp.children, user)
      }
      if (!tmp.children || tmp.children?.length) {
        res.push(tmp)
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  CLEAR_ROUTERS: (state, routes) => {
    state.addRoutes = []
    state.routes = []
  }
}

const actions = {
  generateRoutes({ commit }, user) {
    return new Promise(resolve => {


      // commit('SET_ROUTES', asyncRoutes)
      // resolve(asyncRoutes)
      // return;
      // getRouters().then(res => {
      //   console.log(res)
      // })
      // 在这判断是否有权限，哪些角色拥有哪些权限
      let accessedRoutes
      if (!user.isAdmin) {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, user)
      } else {
        accessedRoutes = asyncRoutes || []
      }

      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  clearRoutes({ commit }) {
    commit('CLEAR_ROUTERS')
  }
}

const permission: Module<any, any> = {
  namespaced: true,
  state,
  mutations,
  actions
}

export default permission
